//
//  SEGActivityWinRecordView.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/8/18.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGActivityWinRecordView.h"

@interface SEGActivityWinRecordView ()
/**
 字体高度
 */
@property (nonatomic, assign) CGFloat textHeight;
/**
  间距
 */
@property (nonatomic, assign) CGFloat padding;


@property (nonatomic, assign) SEGWinReocordViewType type;


@property (nonatomic, strong) UIView *exchangeView;
@property (nonatomic, strong) UIView *firstPageView;
@property (nonatomic, strong) UIView *secondPageView;
@property (nonatomic, strong) NSMutableArray<SEGActivityWinRecordSubView *> *fistPageSubViewArray;
@property (nonatomic, strong) NSMutableArray<SEGActivityWinRecordSubView *> *secondPageSubViewArray;
@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, assign) NSInteger currentPage;

@end

@implementation SEGActivityWinRecordView

- (instancetype)initWithFrame:(CGRect)frame type:(SEGWinReocordViewType)type dataSouce:(NSArray<SEGActivityLotteryUsersModel *> *)dateSouce {
    self = [super initWithFrame:frame];
    if (self) {
        self.type = type;
        [self setupUI];
        [self updateCellWithModelArray:dateSouce];
    }
    return self;
}


- (void)setupUI {
    CGFloat textHeight = 0.0;
    CGFloat padding = 0.0;
    if (self.type == SEGWinReocordViewType_Lottery) {
        textHeight = kLotteryTextFont;
        padding = kLotteryPadding;
    } else {
        textHeight = kTriggerTextFont;
        padding = kTriggerPadding;
    }
    CGFloat exchangeViewHeight = ceil(textHeight*3 + padding*4);
    CGFloat subCellHeight = floorf(exchangeViewHeight/3);
    
    self.exchangeView = [[UIView alloc] init];
    self.exchangeView.clipsToBounds = YES;
    [self addSubview:self.exchangeView];
    [self.exchangeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(exchangeViewHeight);
    }];
    
    CGFloat displayWidth = LYScreenWidth() - 30;
    CGFloat displayHeight = exchangeViewHeight;
    self.firstPageView = [[UIView alloc] init];
    [self.exchangeView addSubview:self.firstPageView];
    self.firstPageView.frame = CGRectMake(0, 0, displayWidth, displayHeight);
    self.fistPageSubViewArray = [NSMutableArray array];
    for (NSInteger i = 0; i < 3; i++) {
        SEGActivityWinRecordSubView *subCell = [[SEGActivityWinRecordSubView alloc] init];
        subCell.frame = CGRectMake(0, i*subCellHeight, displayWidth, subCellHeight);
        [self.fistPageSubViewArray addObject:subCell];
        [self.firstPageView addSubview:subCell];
    }
    
    self.secondPageView = [[UIView alloc] init];
    [self.exchangeView addSubview:self.secondPageView];
    self.secondPageView.frame = CGRectMake(0, displayHeight, displayWidth, displayHeight);
    self.secondPageSubViewArray = [NSMutableArray array];
    for (NSInteger i = 0; i < 3; i++) {
        SEGActivityWinRecordSubView *subCell = [[SEGActivityWinRecordSubView alloc] init];
        subCell.frame = CGRectMake(0, i*subCellHeight, displayWidth, subCellHeight);
        [self.secondPageSubViewArray addObject:subCell];
        [self.secondPageView addSubview:subCell];
    }
    
//    self.layer.borderWidth = 1;
//    self.layer.borderColor = UIColor.redColor.CGColor;
//    self.firstPageView.backgroundColor = UIColor.lightGrayColor;
//    self.secondPageView.backgroundColor = [UIColor.redColor colorWithAlphaComponent:0.3];
//    self.exchangeView.layer.borderWidth = 1;
//    self.exchangeView.layer.borderColor = UIColor.redColor.CGColor;
}

- (void)updateCellWithModelArray:(NSArray<SEGActivityLotteryUsersModel *> *)modelArray {
    // 只赋值一次
    if (!self.lotteryModelArray) {
        self.lotteryModelArray = modelArray;
        
        [self updateSubCellArray:self.fistPageSubViewArray dispalyPage:0];
        [self updateSubCellArray:self.secondPageSubViewArray dispalyPage:1];
        
        if (self.lotteryModelArray.count > 3) {
            if (!self.timer) {
                dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
                self.timer = timer;
                dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
                WeakSelf;
                dispatch_source_set_event_handler(timer, ^{
                    [weakSelf timerRun];
                });
                // 延时三秒触发timer，不然会直接展示第二页
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                     dispatch_resume(timer);
                });
            }
        }
    }
}

- (void)updateSubCellArray:(NSArray *)subCellArray dispalyPage:(NSInteger)page {
    NSInteger allPage = ceil(self.lotteryModelArray.count/3.0);
    NSInteger dispalyPage = page % allPage;
    
    [subCellArray enumerateObjectsUsingBlock:^(SEGActivityWinRecordSubView * _Nonnull subCell, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger modelIndex = dispalyPage * 3 + idx;
        SEGActivityLotteryUsersModel *model = nil;
        if (modelIndex < self.lotteryModelArray.count) {
            model = self.lotteryModelArray[modelIndex];
        }
        [subCell updateUIWithModel:model type:self.type];
    }];
}

- (void)timerRun {
    NSLog(@"✈️ %s", __func__);
    
    CGFloat textHeight = 0.0;
    CGFloat padding = 0.0;
    if (self.type == SEGWinReocordViewType_Lottery) {
        textHeight = kLotteryTextFont;
        padding = kLotteryPadding;
    } else {
        textHeight = kTriggerTextFont;
        padding = kTriggerPadding;
    }
    CGFloat exchangeViewHeight = ceil(textHeight*3 + padding*4);
    
    self.currentPage ++;
    CGFloat displayWidth = LYScreenWidth() - 30;
    CGFloat displayHeight = exchangeViewHeight;
    padding = 0;
    
    [UIView animateWithDuration:1 animations:^{
        self.firstPageView.y -= displayHeight + padding;
        self.secondPageView.y -= displayHeight + padding;
    } completion:^(BOOL finished) {
        if (self.firstPageView.y < -padding) {
            self.firstPageView.frame = CGRectMake(0, displayHeight + padding, displayWidth, displayHeight);
            [self updateSubCellArray:self.fistPageSubViewArray dispalyPage:self.currentPage + 1];
        } else {
            self.secondPageView.frame = CGRectMake(0, displayHeight + padding, displayWidth, displayHeight);
            [self updateSubCellArray:self.secondPageSubViewArray dispalyPage:self.currentPage + 1];
        }
    }];
    
}

@end


@interface SEGActivityWinRecordSubView ()

@property (nonatomic, strong) UILabel *contentLabel;

@end

@implementation SEGActivityWinRecordSubView

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    self.contentLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        [self addSubview:label];
        label;
    });
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}

- (void)updateUIWithModel:(SEGActivityLotteryUsersModel *)model type:(SEGWinReocordViewType)type {
    
    self.contentLabel.text = nil;
    self.contentLabel.attributedText = nil;
    if (!model) {
        return;
    }
    
    CGFloat textHeight = type == SEGWinReocordViewType_Lottery ? kLotteryTextFont : kTriggerTextFont;
    self.contentLabel.font = [UIFont systemFontOfSize:textHeight];

    NSString *time = [SEGUtils stringDateByFormatString:kTimeFormatStringMin withDate:[NSDate dateWithTimeIntervalSince1970:[model.lotteryTime doubleValue]]];
    NSString *text = [NSString stringWithFormat:@"%@ 在 %@ 抽到了 %@",model.nickName,time,model.prizeName];
    if (type == SEGWinReocordViewType_Lottery) {
        self.contentLabel.textColor = kColor_3;
        NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc] initWithString:text];
        NSRange strRange1 = {0,[model.nickName length]};//用户名
        NSRange strRange2 = NSMakeRange(str2.length - model.prizeName.length, model.prizeName.length);
        [str2 addAttribute:NSForegroundColorAttributeName value:kColor_1 range:strRange1];
        [str2 addAttribute:NSForegroundColorAttributeName value:kColor_T range:strRange2];
        self.contentLabel.attributedText = str2;
    } else if (type == SEGWinReocordViewType_RedPackage){
        self.contentLabel.textColor = [UIColor colorWithHexString:@"FBD382"];
        self.contentLabel.text = text;
    } else {
        self.contentLabel.textColor = UIColor.whiteColor;
        self.contentLabel.text = text;
    }
}

@end
